//
//  MultiSegmentContainerView.m
//  HouseFilter
//
//  Created by ET|冰琳 on 15/10/8.
//  Copyright © 2015年 ET|冰琳. All rights reserved.
//

#import "MultiSegmentContainerView.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
@interface MultiSegmentContainerView ()<SegmentSelectProtocol>
{
    UIView *_keywindowContainer;
}

@property (nonatomic) BIMultiSegmentControl *segmentControl;

@end


@implementation MultiSegmentContainerView

- (instancetype)initWithSegmentControl:(BIMultiSegmentControl *)control {
    if (self = [super initWithFrame:control.bounds]) {
        self.backgroundColor = [UIColor clearColor];
        [self addSubview:control];
        self.segmentControl = control;
        control.delegate = self;
        
        UIView *windowContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 0)];
        _keywindowContainer = windowContainer;
        
        _keywindowContainer.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    }
    return self;
}

- (void)segmentControlDidSelectIndex:(NSInteger)index{
    
    UIView *viewToAdd = [self.delegate segmentContainerSubViewForIndex:index];
    if ([self.delegate respondsToSelector:@selector(segmentContainerWillDisplaySubView:index:)]) {
        [self.delegate segmentContainerWillDisplaySubView:viewToAdd index:index];
    }
    
    
    CGRect frame = [self convertRect:self.bounds toView:[UIApplication sharedApplication].keyWindow];
    CGRect keyWindowContainerFrame = CGRectMake(0, CGRectGetMaxY(frame), self.frame.size.width,  - CGRectGetMaxY(frame));
    
    _keywindowContainer.frame = keyWindowContainerFrame;
    [_keywindowContainer addSubview:viewToAdd];

    [[UIApplication sharedApplication].keyWindow addSubview:_keywindowContainer];
}


- (void)segmentControlDeSelectIndex:(NSInteger)index{
    UIView *viewToRemove = [self.delegate segmentContainerSubViewForIndex:index];
    
    if ([self.delegate respondsToSelector:@selector(segmentContainerWillEndDisplaySubView:index:)]) {
        [self.delegate segmentContainerWillEndDisplaySubView:viewToRemove index:index];
    }
    [viewToRemove removeFromSuperview];
}

@end